// 读书
import cheerio from 'cheerio'
import Axios from 'axios'
const currentKey = '20xs'
const config = {
  '20xs': 'https://www.20xs.la/dingdian/84_84720/'
}
function formatChapterList (str) {
  let $ = cheerio.load(str)
  const ret = []
  if (currentKey === '20xs') {
    // 解析文件
    // console.log($('#wrapper .box_con #list dd a'))
    $('#wrapper .box_con #list dd a').each((i, ele) => {
      if (ele.type === 'tag' && ele.name === 'a') {
        ret.push({
          label: ele.children[0].data,
          link: ele.attribs.href
        })
      }
    })
  }
  return ret
}
// 获取章节列表
export function getWebChapter () {
  return new Promise((resolve, reject) => {
    // loadhtml
    Axios.get(config[currentKey]).then(res => {
      // console.log(res.data)
      const chapter = formatChapterList(res.data)
      // console.log(chapter)
      if (chapter) {
        resolve(chapter)
      } else {
        reject(new Error('错误'))
      }
    })
  })
}
function formatXSDetail (str, label, type) {
  let ret = []
  if (type === 'str') {
    ret = ''
  }
  let $ = cheerio.load(str)
  if (currentKey === '20xs') {
    // id=content
    $('#content p').each((i, ele) => {
      if (ele.type === 'tag' && ele.name === 'p') {
        if (type === 'str') {
          ret = ret + label + '\n\n'
          ret = ret + ele.children[0].data + '\n\n'
        } else {
          ret.push(ele.children[0].data)
        }
      }
    })
  }
  return ret
}
// 获取章节详情
export function getWebXSDetail (url, label, type) {
  return new Promise((resolve, reject) => {
    url = url.indexOf(0) === '/' ? url : '/' + url
    Axios.get(new URL(config[currentKey]).origin + url).then(res => {
      // console.log(res.data)
      const chapter = formatXSDetail(res.data, label, type)
      // console.log(chapter)
      if (chapter) {
        resolve(chapter)
      } else {
        reject(new Error('错误'))
      }
    })
  })
}

export function laodWebXS () {
  getWebChapter().then(res => {
    res.forEach((item, idx) => {
      if (idx < 10) return
      getWebXSDetail(item.link, item.label, 'str').then(ret => {
        console.log(ret)
      })
    })
  })
}
